package com.orange.cetback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.cetback.common.properties.YoudaoProperties;
import com.orange.cetback.common.utils.AuthV3Util;
import com.orange.cetback.common.utils.HttpUtil;
import com.orange.cetback.pojo.dto.DictionaryDTO;
import com.orange.cetback.pojo.entity.Dictionary;
import com.orange.cetback.mapper.DictionaryMapper;
import com.orange.cetback.service.DictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-04-07
 */
@Slf4j
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements DictionaryService {
    @Autowired
    private YoudaoProperties youdaoProperties;
    @Override
    public Dictionary queryDictionary(DictionaryDTO dictionaryDTO) {
        //数据库有则直接查询，若没有再查询接口
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getQuery,dictionaryDTO.getQuery());
        if(!dictionaryDTO.getFrom().equals("auto")){
            queryWrapper.eq(Dictionary::getFrom,dictionaryDTO.getFrom());
        }
        queryWrapper.eq(Dictionary::getTo,dictionaryDTO.getTo());
        Dictionary dictionary = this.getOne(queryWrapper);
        if (dictionary != null){
            return dictionary;
        }
        log.info("走到api");
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(dictionaryDTO);
        try {
            // 添加鉴权相关参数
            AuthV3Util.addAuthParams(youdaoProperties.getAppKey(), youdaoProperties.getAppSecret(), params);
            byte[] result = HttpUtil.doPost(youdaoProperties.getTranslateUrl(), null, params, "application/json");
            String responseJson = new String(result, StandardCharsets.UTF_8);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(responseJson);
                String query = rootNode.path("query").asText();
                String translation = "";
                JsonNode translationArray = rootNode.get("translation");
                if (translationArray != null && translationArray.isArray()) {
                    translation = StreamSupport.stream(translationArray.spliterator(), false)
                            .map(JsonNode::asText)
                            .collect(Collectors.joining(", "));
                }
                String speakUrl = rootNode.path("speakUrl").asText();
                String tSpeakUrl = rootNode.path("tSpeakUrl").asText();
                String l = rootNode.path("l").asText();
                dictionary = new Dictionary();
                dictionary.setQuery(query);
                dictionary.setTranslation(translation);
                dictionary.setFrom(l.split("2")[0]);
                dictionary.setTo(l.split("2")[1]);
                dictionary.setSpeakUrl(speakUrl);
                dictionary.setTSpeakUrl(tSpeakUrl);
                this.baseMapper.insert(dictionary);
            }catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }catch (NoSuchAlgorithmException e){
            throw new RuntimeException(e);
        }
        return dictionary;
    }

    private static Map<String, String[]> createRequestParams(DictionaryDTO dictionaryDTO) {
        return new HashMap<String, String[]>() {{
            put("q", new String[]{dictionaryDTO.getQuery()});
            put("from", new String[]{dictionaryDTO.getFrom()});
            put("to", new String[]{dictionaryDTO.getTo()});
            put("voice", new String[]{dictionaryDTO.getVoice()});
        }};
    }
}
